import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user'
import { insertCartService, getNewCartList, delCartService } from '@/apis/cart'
// 存储购物车数据
export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = userStore.userInfo.token
    // 1、添加购物车
    const getCartList = async (goods) => {
      // 10、判断是否登录，若登录，走接口逻辑
      if (isLogin) {
        // 10.1 将数据通过接口提交进后台购物车
        await insertCartService({
          skuId: goods.skuId,
          count: goods.count
        })
        updateNewList()
      } else {
        // 处理添加购物车逻辑(未登录状态)
        const item = cartList.value.find((item) => item.skuId === goods.skuId)
        if (item) {
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }
    // 2、删除购物车数据
    const delCart = async (skuId) => {
      if (isLogin) {
        await delCartService([skuId])
        updateNewList()
      } else {
        const index = cartList.value.findIndex((item) => skuId === item.skuId)
        cartList.value.splice(index, 1)
      }
    }
    // 10.2 获取最新的购物车数据，复制给本地数据列表
    const updateNewList = async () => {
      const res = await getNewCartList()
      cartList.value = res.result
    }

    // 3、计算购物车中的商品总数
    const allCount = computed(() =>
      cartList.value.reduce((sum, item) => sum + item.count, 0)
    )
    // 4、计算商品总价
    const allPrice = computed(() =>
      cartList.value.reduce((sum, item) => sum + item.count * item.price, 0)
    )
    // 5、单选功能切换逻辑
    const changeSelected = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }
    // 6、判断是否全选，将boolean值赋值给全选框
    const isAll = computed(() => {
      return cartList.value.every((item) => item.selected === true)
    })
    // 7、全选调动单选
    const allSelected = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected))
    }
    // 8、计算已选中的商品总数
    const selectedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((sum, item) => sum + item.count, 0)
    })
    // 9、计算已选中商品的总价
    const selectedPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((sum, item) => sum + item.count * item.price, 0)
    })
    // 11、退出登录，清除购物车数据
    const clearCart = () => {
      cartList.value = []
    }
    return {
      cartList,
      allCount,
      allPrice,
      isAll,
      getCartList,
      delCart,
      changeSelected,
      allSelected,
      selectedCount,
      selectedPrice,
      clearCart,
      updateNewList
    }
  },
  {
    persist: true
  }
)
